﻿using Common;
using Common.Extend;
using Common.Helper;
using FreeSql.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using System.Threading.Tasks;

namespace enterprise.Website.Core.Filter
{
    /// <summary>
    /// 后台管理登录验证Filter
    /// </summary>
    public class LoginAuthorizeAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string sessionValue = context.HttpContext.Session.GetString(SystemConstConfig.AuthHeader);
            var sessionJson = AESEncryptHelper.Decode(sessionValue);
            var adminInfo = sessionJson.ToObject<UserInfo>();
            if (adminInfo != null && adminInfo.Id > 0)
            {
                await base.OnActionExecutionAsync(context, next);
                return;
            }
            else//没有登录，则返回登录，如果是API请求，返回json，如果是浏览器请求重定向页面
            {
                if (context.HttpContext.Request.IsApiReuest() || context.HttpContext.Request.IsAjax())
                {
                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    context.HttpContext.Response.ContentType = "application/json;charset=UTF-8";
                    await context.HttpContext.Response.WriteAsync(new ApiResult
                    {
                        Success = false,
                        Message = "请登录以后再进行操作",
                        StatusCode = (int)HttpStatusCode.Unauthorized
                    }.ToJson());
                }
                else
                {
                    context.HttpContext.Response.Redirect("/manage/login");
                }
            }
        }
    }
}
